package com.contract.commonlib.http.intercept

import cn.woochen.comlib.util.UserPref
import com.blankj.utilcode.util.Utils
import com.contract.commonlib.config.Constants
import com.contract.commonlib.http.SignUtils
import com.contract.commonlib.util.DeviceInfoUtil
import com.contract.commonlib.util.PackageUtil
import com.contract.commonlib.util.ext.logcom
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.util.*

/**
 * @author: witness
 * created: 2021/9/17
 * desc:
 */
class HttpCommonInterceptor : Interceptor {
    private var mToken by UserPref(Constants.USER_TOKEN, "")
    private var mImei by UserPref(Constants.IMEI, "")

    companion object {
        val mBodyParamsMap: MutableMap<String, String> = mutableMapOf()
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val currentTimeMillis = System.currentTimeMillis().toString() + ""
        var imei = mImei
        if (imei.isBlank()) imei = DeviceInfoUtil.getIMEI(Utils.getApp())
        //添加公共参数
        mBodyParamsMap["token"] = mToken
        mBodyParamsMap["version"] = PackageUtil.getCurrentVersionName(Utils.getApp())
        mBodyParamsMap["deviceNo"] = imei
        mBodyParamsMap["channel"] = "2"
        mBodyParamsMap["ts"] = currentTimeMillis

        val request = chain.request()
        val newBuilder = request.newBuilder()
        val md5Signa: String = SignUtils.getMd5Signa(request, mBodyParamsMap)
        mBodyParamsMap["sign"] = md5Signa
        val body = request.body
        if (body is FormBody) {
            val formBodyParamMap: MutableMap<String, String> = HashMap()
            val bodySize = body.size
            for (i in 0 until bodySize) {
                formBodyParamMap[body.name(i)] = body.value(i)
            }
            val newFormBodyParamMap = mBodyParamsMap
            formBodyParamMap.putAll(newFormBodyParamMap)
            val bodyBuilder = FormBody.Builder()
            for ((key, value) in formBodyParamMap) {
                bodyBuilder.add(key, value)
            }
            newBuilder.method(request.method, bodyBuilder.build())
            return chain.proceed(newBuilder.build())
        }
        else {
            val getBuilder = request.url.newBuilder();
            for ((key, value) in mBodyParamsMap) {
                getBuilder.addQueryParameter(key, value)
            }
            val modifiedUrl = getBuilder.build()
            val build = newBuilder.url(modifiedUrl).build()
            logcom(
                "requestBody::", modifiedUrl.toUrl().query
            )
            return chain.proceed(build)
        }

    }
}